//
//  SGFYSViewController_detail.m
//  Estate
//
//  Created by wangdongdong on 16/7/11.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "SGFYSViewController_detail.h"
#import "TableTopStateCell.h"
#import "B_wuLiaoCell.h"
#import "DefaineCell.h"
#import "QianDTableCell.h"
#import "FDAlertView.h"
#import "AlertVIew.h"
#import "ProcessRecordModel.h"
#import "AttachmentMessageCell.h"
#import "H1_ImagesCell.h"
#import "PictureViewController.h"


#import "ChooseMaterialCell.h"
#import "ProcessModel.h"

@interface SGFYSViewController_detail ()<UITableViewDataSource, UITableViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{
    FDAlertView *alert;
}

/**表格*/
@property (nonatomic, strong) TPKeyboardAvoidingTableView *tableView;
/**流程表模型*/
@property (nonatomic, strong) ProcessModel *pModel;
// 流程记录表模型
@property (nonatomic, strong) ProcessRecordModel *pRecordModel;
// 标题
@property (nonatomic, copy) NSString *titleStr;
// 内容
@property (nonatomic, copy) NSString *content;
@property (strong, nonatomic) Tweet *curTweet;  /** 附件模型*/
@property (strong, nonatomic) NSMutableArray *selectedAssetURLs;

// 图片附件ID(fileId)
@property (strong, nonatomic) NSMutableArray *fileIdArr;

// 是否合格
@property (assign, nonatomic) BOOL buhege;

// 隐蔽
@property (copy, nonatomic) NSString *ybButton;
// 检验
@property (copy, nonatomic) NSString *jyButton;
// 分项
@property (copy, nonatomic) NSString *fxButton;
// 施工
@property (copy, nonatomic) NSString *sgButton;
// 其他
@property (copy, nonatomic) NSString *otherButton;

@end


@implementation SGFYSViewController_detail

- (TPKeyboardAvoidingTableView *)tableView{
    if(_tableView==nil){
        _tableView=[[TPKeyboardAvoidingTableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT)];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.bounces=NO;
    }
    return _tableView;
}


- (NSMutableArray *)selectedAssetURLs{
    if(!_selectedAssetURLs){
        _selectedAssetURLs=[NSMutableArray array];
    }
    return _selectedAssetURLs;
}

- (NSMutableArray *)fileIdArr {
    if (_fileIdArr) {
        _fileIdArr = [NSMutableArray array];
    }
    return _fileIdArr;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    _curTweet = [[Tweet alloc] init];
    self.title=@"验收单";
    //注册单元格
    [self.tableView registerNib:[UINib nibWithNibName:@"TableTopStateCell" bundle:nil] forCellReuseIdentifier:@"topCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"B_wuLiaoCell" bundle:nil] forCellReuseIdentifier:@"tCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DefaineCell" bundle:nil] forCellReuseIdentifier:@"fCell"];
    [self.tableView registerClass:[AttachmentMessageCell class] forCellReuseIdentifier:@"amCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"QianDTableCell" bundle:nil] forCellReuseIdentifier:@"qCell"];
    [_tableView registerClass:[H1_ImagesCell class] forCellReuseIdentifier:kCellIdentifier_H1_ImagesCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"ChooseMaterialCell" bundle:nil] forCellReuseIdentifier:@"chooseMaterial"];
    
    // 获取流程信息
    self.pModel = [self findProcessData];
    // 获取记录信息
    self.pRecordModel = [self findDataSource:self.processID];
    
    // 获取附件数据
    [self getAttachment];
    [self refresh:nil];
    
    if (!self.zongJian) {
        self.buhege = (self.pModel.PROCESS_STAGE == PROCESS_STAGE_CHECK_PASS_YES_NO || self.pModel.PROCESS_STAGE == PROCESS_STAGE_REVIEW_PASS_NO || self.pModel.PROCESS_STAGE == PROCESS_STAGE_DOING);
    }
    
    if (self.buhege) {
        //添加右上方提交按钮
        self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"wancheng"] style:UIBarButtonItemStyleDone target:self action:@selector(clickSave)];
    }
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(refresh:) name:@"RefreshImage_editYS" object:nil];
}


- (void)refresh:(id)sender{
    if(self.selectedAssetURLs != nil){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            self.curTweet.selectedAssetURLs = self.selectedAssetURLs;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:3]] withRowAnimation:UITableViewRowAnimationFade];
            });
        });
    }
    self.curTweet.selectedAssetURLs = self.selectedAssetURLs;
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:3]] withRowAnimation:UITableViewRowAnimationFade];
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view resignFirstResponder];
}

// 获取流程信息
- (ProcessModel *)findProcessData {
    // 获取数据库
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    // 打开数据库
    [db open];
    // 准备sql语句
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM PROCESS WHERE ID = '%@' ORDER BY CREATE_TIME DESC", self.processID];
    // 查找数据
    FMResultSet *result = [db executeQuery:sql];
    ProcessModel *prModel = [[ProcessModel alloc] init];
    
    while ([result next]) {
        prModel.ID = DEFISNUL([result stringForColumn:@"ID"]);
        prModel.PRO_ID =  DEFISNUL([result stringForColumn:@"PRO_ID"]);
        prModel.ADDRESS_ID =  DEFISNUL([result stringForColumn:@"ADDRESS_ID"]);
        prModel.ADDRES_INFO =  DEFISNUL([result stringForColumn:@"ADDRES_INFO"]);
        prModel.PROCESS_TYPE = [result intForColumn:@"PROCESS_TYPE"];
        prModel.PROCESS_STAGE = [result intForColumn:@"PROCESS_STAGE"];
        prModel.PROCESS_PUBLISHERS =  DEFISNUL([result stringForColumn:@"PROCESS_PUBLISHERS"]);
        prModel.PROCESS_MASTERS = [result stringForColumn:@"PROCESS_MASTERS"];
        prModel.PROCESS_RECIFY_USERS = [result stringForColumn:@"PROCESS_RECIFY_USERS"];
        prModel.PROCESS_RECIFY_UNITS = [result stringForColumn:@"PROCESS_RECIFY_UNITS"];
        prModel.RECIFY_REVIEW_USERS = [result stringForColumn:@"RECIFY_REVIEW_USERS"];
        prModel.BEGIN_TIME = [result stringForColumn:@"BEGIN_TIME"];
        prModel.REQUIRED_END_TIME = [result stringForColumn:@"REQUIRED_END_TIME"];
        prModel.END_TIME = [result stringForColumn:@"END_TIME"];
        prModel.PROCESS_TITLE = [result stringForColumn:@"PROCESS_TITLE"];
        prModel.PROCESS_NUMBER = [result stringForColumn:@"PROCESS_NUMBER"];
        prModel.EXTEND_INFO = [result stringForColumn:@"EXTEND_INFO"];
        prModel.CREATE_USER_NAME = [result stringForColumn:@"CREATE_USER_NAME"];
        prModel.CREATE_TIME = [result stringForColumn:@"CREATE_TIME"];
        prModel.CREATE_IP = [result stringForColumn:@"CREATE_IP"];
        prModel.MODIFY_USER_NAME = [result stringForColumn:@"MODIFY_USER_NAME"];
        prModel.MODIFY_IP = [result stringForColumn:@"MODIFY_IP"];
        prModel.MODIFY_TIME = [result stringForColumn:@"MODIFY_TIME"];
        break;
    }
    [db close];
    return prModel;
}

// 获取记录信息
- (ProcessRecordModel *)findDataSource:(NSString *)ID {
    // 获取数据库
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    // 打开数据库
    [db open];
    // 准备sql语句
    NSString *sql = [NSString stringWithFormat:@"SELECT *, time(CREATE_TIME), date(CREATE_TIME) FROM PROCESS_RECORD WHERE PROCESS_ID = '%@' ORDER BY CREATE_TIME DESC", ID];
    // 查找数据
    FMResultSet *result = [db executeQuery:sql];
    ProcessRecordModel *prModel = [[ProcessRecordModel alloc] init];
    while ([result next]) {
        prModel.ID = DEFISNUL([result stringForColumn:@"ID"]);
        prModel.PRO_ID =  DEFISNUL([result stringForColumn:@"PRO_ID"]);
        prModel.PROCESS_ID =  DEFISNUL([result stringForColumn:@"PROCESS_ID"]);
        prModel.ADDRESS_ID =  DEFISNUL([result stringForColumn:@"ADDRESS_ID"]);
        prModel.ADDRES_INFO =  DEFISNUL([result stringForColumn:@"ADDRES_INFO"]);
        prModel.PROCESS_TYPE = [result intForColumn:@"PROCESS_TYPE"];
        prModel.PROCESS_STAGE = [result intForColumn:@"PROCESS_STAGE"];
        prModel.RECORD_USER =  DEFISNUL([result stringForColumn:@"RECORD_USER"]);
        prModel.RECORD_MASTER = [result stringForColumn:@"RECORD_MASTER"];
        prModel.RECIFY_USER = [result stringForColumn:@"RECIFY_USER"];
        prModel.RECIFY_UNIT = [result stringForColumn:@"RECIFY_UNIT"];
        prModel.SEVERITY = [result stringForColumn:@"SEVERITY"];
        prModel.END_TIME = [result stringForColumn:@"END_TIME"];
        prModel.SEND_TIME = [result stringForColumn:@"SEND_TIME"];
        prModel.SEND_TYPE = [result intForColumn:@"SEND_TYPE"];
        prModel.PROCESS_TITLE = [result stringForColumn:@"PROCESS_TITLE"];
        prModel.PROCESS_CONTENT = [result stringForColumn:@"PROCESS_CONTENT"];
        prModel.PROCESS_REQUIRED = [result stringForColumn:@"PROCESS_REQUIRED"];
        prModel.PROCESS_DESC = [result stringForColumn:@"PROCESS_DESC"];
        prModel.SUBMITTORS = [result stringForColumn:@"SUBMITTORS"];
        prModel.PUT_USER = [result stringForColumn:@"PUT_USER"];
        prModel.REVIEW_OPINION = [result stringForColumn:@"REVIEW_OPINION"];
        prModel.FILEINFOS = [result stringForColumn:@"FILEINFOS"];
        prModel.EXTEND_INFO = [result stringForColumn:@"EXTEND_INFO"];
        prModel.CREATE_USER_NAME = [result stringForColumn:@"CREATE_USER_NAME"];
        prModel.CREATE_TIME = [result stringForColumn:@"CREATE_TIME"];
        prModel.CREATE_DATE = [result stringForColumn:@"date(CREATE_TIME)"];
        prModel.SUBCREATE_TIME = [result stringForColumn:@"time(CREATE_TIME)"];
        prModel.zhuangtai = [result intForColumn:@"REVIEW_STATE"];
        break;
    }
    [db close];
    return prModel;
}



// 获取附件数据
- (void)getAttachment {
    //设置附件
    NSArray *imageArr=[LSUtility dictionaryWithJsonString:self.pRecordModel.FILEINFOS];
    
    // 查询附件表
    if(imageArr.count>0){
        for (NSDictionary *imageDic in imageArr) {
            NSString *fileId = imageDic[@"fileId"];
            // 记录当前图片附件的ID
            [self.fileIdArr addObject:fileId];
            
            NSString *fileName=[LSUtility queryAttachment:fileId][@"FILE_NAME"];
            NSString *filePath=[DEF_FILE_PATH stringByAppendingString:
                                [NSString stringWithFormat:@"/%@",fileName]];
            [self.selectedAssetURLs addObject:filePath];
        }
    }
    
    self.curTweet.selectedAssetURLs = self.selectedAssetURLs;
}


#pragma mark- UITaleViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section == 0 || section == 3){
        return 0.001;
    }else{
        return 10;
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section==0){
        return 7;
    }else if (section==1){
        return 3;
    }
    else{
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    long section=indexPath.section;
    long row=indexPath.row;
    if(section==0){
        return 44;
    }else if(section==1){
        if(row==0){
            return 44;
        }else{
            return 100;
        }
    } else if (section == 2) {
        if (self.buhege) {
            return 150;
        } else {
            if (![self.pRecordModel.PROCESS_DESC isEqualToString:@""]) {
                NSArray *descArr = [self.pRecordModel.PROCESS_DESC componentsSeparatedByString:@"/"];
                CGFloat margin = 5;
                CGFloat H = 15;
                return descArr.count * (margin + H) + 25;
            } else {
                return 25;
            }
        }
    } else {
        return  [H1_ImagesCell cellHeightWithObj:_curTweet title:@"图片"];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //组
    long section = indexPath.section;
    //行
    long row=indexPath.row;
    if(section == 0){
        if(row == 0){
            TableTopStateCell *cell = [tableView dequeueReusableCellWithIdentifier:@"topCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.title.text = [NSString stringWithFormat:@"%@ 验收单", self.pRecordModel.CREATE_DATE];
            return cell;
        }else{
            DefaineCell *cell = [tableView dequeueReusableCellWithIdentifier:@"fCell" forIndexPath:indexPath];
            if(row==1){
                cell.title.text = @"项  目:";
                cell.text.text = [LSUtility getProjectNameByProjectId:self.pRecordModel.PRO_ID][@"PROJECT_NAME"];
                return cell;
            }else if (row == 2){
                cell.title.text = @"位  置:";
                NSDictionary *dic;
                dic = [LSUtility dictionaryWithJsonString:self.pModel.EXTEND_INFO];
                cell.text.text = dic[@"address"];
                return cell;
                
            } else if (row == 3){
                cell.title.text = @"监  理:";
                cell.text.text = [LSUtility getuserIdByUserName:self.pRecordModel.RECORD_MASTER][@"REAL_NAME"];
                return cell;
            } else if (row == 4){
                cell.title.text = @"报送人:";
                cell.text.text = [LSUtility getuserIdByUserName:self.pModel.PROCESS_PUBLISHERS][@"REAL_NAME"];
                return cell;
                
            } else if (row == 5) {
                cell.title.text = @"编  号:";
                cell.text.text = DEFISNUL(self.pModel.PROCESS_NUMBER) ;
                return cell;
                
            } else{
                cell.title.text = @"时  间:";
//                cell.text.text = self.pRecordModel.CREATE_TIME;
                cell.text.text = self.pModel.CREATE_TIME;
                return cell;
            }
        }
    }
    else if(section==1) {
        if(row==0){
            QianDTableCell *cell=[tableView dequeueReusableCellWithIdentifier:@"qCell" forIndexPath:indexPath];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            cell.title.text = @"标  题:";
            cell.textField.text = self.pRecordModel.PROCESS_TITLE;
            cell.textField.placeholder = @"请输入标题";
            
            if (self.buhege) {
                cell.textValueChangedBlock = ^(NSString *tStr) {
                    self.titleStr = tStr;
                };
            } else {
                cell.isedit = NO;
            }
            return cell;
        }else{
            B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"tCell" forIndexPath:indexPath];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            
            if(row==1){
                cell.title.text=@"内  容:";
                cell.text.placeholder = @"";
                cell.text.text = self.pRecordModel.PROCESS_CONTENT;
                if (self.buhege) {
                    cell.textValueChangedBlock = ^(NSString *cStr) {
                        self.content = cStr;
                    };
                } else {
                    cell.isEdit = NO;
                }
                return cell;
            } else {
                cell.title.text=@"意  见:";
                cell.text.placeholder = @"";
                cell.isEdit = NO;
                cell.text.text = self.pRecordModel.REVIEW_OPINION;
                return cell;
            }
        }
    } else if (section == 2) {
        if (self.buhege) {
            // 附件类型
            ChooseMaterialCell *cell=[tableView dequeueReusableCellWithIdentifier:@"chooseMaterial" forIndexPath:indexPath];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            
            //勾选上已经选择的项
            if (![self.pRecordModel.PROCESS_DESC isEqualToString:@""]&&self.pRecordModel) {
                NSArray *descArr = [self.pRecordModel.PROCESS_DESC componentsSeparatedByString:@"/"];
                //                for (NSString *str in descArr) {
                //                    DeLog(@"%@",str);
                //
                //                }
                
                if([descArr containsObject:@"隐蔽工程质量检验资料"]){
                    cell.ybgcBtn.selected=YES;
                    self.ybButton=@"隐蔽工程质量检验资料";
                }
                if ([descArr containsObject:@"检验批质量检验资料"]){
                    cell.jcplBtn.selected=YES;
                    self.jyButton=@"检验批质量检验资料";
                }
                if ([descArr containsObject:@"分项工程质量检验资料"]){
                    cell.fxgcBtn.selected=YES;
                    self.fxButton=@"分项工程质量检验资料";
                }
                if([descArr containsObject:@"施工实验室质量检验资料"]){
                    cell.sgBtn.selected=YES;
                    self.sgButton=@"施工实验室质量检验资料";
                }
                if([descArr containsObject:@"其他"]){
                    cell.qtBtn.selected=YES;
                    self.otherButton=@"其他";
                }
            }
            
            
            // 隐蔽
            cell.ybBlock = ^(NSString *ybStr) {
                self.ybButton = ybStr;
            };
            // 检验
            cell.jyBlock = ^(NSString *jyStr) {
                self.jyButton = jyStr;
            };
            // 分项
            cell.fxBlock = ^(NSString *fxStr) {
                self.fxButton = fxStr;
            };
            // 施工
            cell.sgBlock = ^(NSString *sgStr) {
                self.sgButton = sgStr;
            };
            // 其他
            cell.otherBlock = ^(NSString *otherStr) {
                self.otherButton = otherStr;
            };
            return  cell;
            
        } else {
            AttachmentMessageCell *cell = [[AttachmentMessageCell alloc] initWithReuseIdentifier:@"amCell" withModel:self.pRecordModel];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            return cell;
        }
        
    } else {
        WEAKSELF
        H1_ImagesCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_H1_ImagesCell forIndexPath:indexPath];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        if (self.buhege) {
            cell.isEdit = YES;
        } else {
            cell.isEdit = NO;
        }
        [cell setTitleColor:[UIColor colorWithRed:0.22 green:0.64 blue:0.59 alpha:1.00]];
        cell.curTweet = _curTweet;
        cell.addPicturesBlock = ^(){
            [weakSelf showActionForPhoto];
        };
        
        cell.deleteTweetImageBlockUrl= ^(TweetImage *toDelete,NSString *deUrl){
            //移除图片
            [weakSelf.curTweet deleteATweetImage:toDelete];
            //移除数组
            [weakSelf.selectedAssetURLs removeObject:deUrl];
            
            [weakSelf refresh:nil];
        };
        return cell;
    }
}

#pragma mark--保存
- (void)clickSave {
    if (!self.titleStr) {
        self.titleStr = self.pRecordModel.PROCESS_TITLE;
    }
    if ([self.titleStr isEqual:@""]) {
        [LSUtility showToastWithMessage:@"请输入标题" inView:self.view Andtime:1.];
    } else {
        // 先删除图片附件
        [self deleteLastData];
        // 修改流程
        [self modifyFlow];
        // 添加流程记录
        [self addFlowRecordData];
        
        // 通知列表页刷新数据
        [[NSNotificationCenter defaultCenter] postNotificationName:@"editYS" object:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

// 删除图片附件
-(void)deleteLastData {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    //删除的图片 附件表设置为del
    for (NSString *ids in self.fileIdArr) {
        
        NSString *sqlStr=[NSString stringWithFormat:@"update attachment set LOCAL_MODIFY_STATE='DEL' where id='%@'",ids];
        BOOL isok=[db executeUpdate:sqlStr];
        if (isok) {
            NSLog(@"更改删除状态成功");
        } else {
            NSLog(@"更改删除状态失败");
        }
        
    }
    
    
    [db close];
}

// 修改流程
- (void)modifyFlow {
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    // 修改流程
    NSString *sqlStr2 = [NSString stringWithFormat:@"UPDATE PROCESS SET PROCESS_TITLE = '%@', PROCESS_STAGE = 1, LOCAL_MODIFY_STATE = 'MOD', PROCESS_RECIFY_USERS = '%@', MODIFY_USER_NAME = '%@', MODIFY_IP = '%@', MODIFY_TIME = '%@' WHERE ID = '%@'", self.titleStr, USERID, DEF_PERSISTENT_GET_OBJECT(@"realname"), [LSUtility getIPAddress], [LSUtility nowTime], self.processID];
    if([db executeUpdate:sqlStr2]) {
        NSLog(@"修改成功");
    } else {
        NSLog(@"修改失败");
    }
    [db close];
}

#pragma mark - 新增数据(流程记录表)
- (void)addFlowRecordData {
    ProcessRecordModel *model = self.pRecordModel;
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelper=[DBHelper help];
    
    // 施工方说明
    NSString *sgfState;
    if (self.ybButton && ![self.ybButton isEqualToString:@""]) {
        sgfState = self.ybButton;
    }
    if (self.jyButton && sgfState) {
        sgfState = [sgfState stringByAppendingFormat:@"/%@", self.jyButton];
    } else if (self.jyButton && ![self.jyButton isEqualToString:@""]) {
        sgfState = self.jyButton;
    }
    if (self.fxButton && sgfState) {
        sgfState = [sgfState stringByAppendingFormat:@"/%@", self.fxButton];
    } else if (self.fxButton && ![self.fxButton isEqualToString:@""]) {
        sgfState = self.fxButton;
    }
    if (self.sgButton && sgfState) {
        sgfState = [sgfState stringByAppendingFormat:@"/%@", self.sgButton];
    } else if (self.sgButton && ![self.sgButton isEqualToString:@""]) {
        sgfState = self.sgButton;
    }
    if (self.otherButton && sgfState) {
        sgfState = [sgfState stringByAppendingFormat:@"/%@", self.otherButton];
    } else if(self.otherButton && ![self.otherButton isEqualToString:@""]) {
        sgfState = self.otherButton;
    }
    
    sgfState = sgfState ? sgfState : self.pRecordModel.PROCESS_DESC;
    // 内容
    if (!self.content) {
        self.content = self.pRecordModel.PROCESS_CONTENT;
    }
    // 流程记录ID
    NSString *ID = [NSUUID UUID].UUIDString;
    // 附件信息
    NSArray *fileinfosArr = [self insertAttachment:ID];
    
    NSString *fileinfosStr;
    if (fileinfosArr) {
        fileinfosStr = [self toJSONData:fileinfosArr];
    }
    //字段及对应值
    NSDictionary *pragameDic=[NSDictionary dictionary];
    pragameDic=@{
                 @"ID":ID,
                 @"PRO_ID":DEFISNUL(model.PRO_ID),
                 @"PROCESS_ID":DEFISNUL(self.processID),
                 @"WEATHER":DEFISNUL(model.WEATHER),
                 @"ADDRESS_ID":DEFISNUL(model.ADDRESS_ID),
                 @"ADDRES_INFO":DEFISNUL(model.ADDRES_INFO),
                 @"PROCESS_TYPE":[NSString stringWithFormat:@"%ld", (long)model.PROCESS_TYPE],
                 @"PROCESS_STAGE":[NSString stringWithFormat:@"%d",1],
                 @"RECORD_USER":USERID,
                 @"PROBLEM_TYPE":[NSString stringWithFormat:@"%ld", (long)model.PROBLEM_TYPE],
                 @"RECORD_MASTER":DEFISNUL(model.RECORD_MASTER),
                 @"RECIFY_USER":DEFISNUL(model.RECIFY_USER),
                 @"RECIFY_UNIT":DEFISNUL(model.RECIFY_UNIT),
                 @"SEVERITY":DEFISNUL(model.SEVERITY),
                 @"END_TIME":DEFISNUL(model.END_TIME),
                 @"SEND_TIME":[LSUtility nowTime],
                 @"SEND_TYPE":DEFISNUL(model.SEND_TIME),
                 @"PROCESS_TITLE":DEFISNUL(self.titleStr),
                 @"PROCESS_CONTENT":DEFISNUL(self.content),
                 @"PROCESS_REQUIRED":DEFISNUL(model.PROCESS_REQUIRED),
                 @"PROCESS_DESC":DEFISNUL(sgfState),
                 @"SUBMITTORS":DEFISNUL(model.SUBMITTORS),
                 @"PUT_USER":DEFISNUL(model.PUT_USER),
                 @"REVIEW_USER":USERID,
                 @"REVIEW_OPINION":DEFISNUL(model.REVIEW_OPINION),
                 @"REVIEW_STATE":[NSString stringWithFormat:@"%ld", (long)model.REVIEW_STATE],
                 @"FILEINFOS":DEFISNUL(fileinfosStr),
                 @"EXTEND_INFO":DEFISNUL(model.EXTEND_INFO),
                 @"CREATE_USER_NAME":USERID,
                 @"CREATE_TIME":[LSUtility nowTime],
                 @"CREATE_IP":[LSUtility getIPAddress],
                 @"MODIFY_USER_NAME":USERID,
                 @"MODIFY_IP":[LSUtility getIPAddress],
                 @"MODIFY_TIME":[LSUtility nowTime],
                 @"LOCAL_MODIFY_USER_NAME":USERID,
                 @"LOCAL_MODIFY_TIME":[LSUtility nowTime],
                 @"LOCAL_MODIFY_STATE":@"ADD",
                 };
    if (!pragameDic) {
        return;
    }
    BOOL isAdd=[dbhelper DataBase:db insertKeyValues:pragameDic intoTable:PROCESS_RECORD];
    if(isAdd){
        NSLog(@"验收记录新增成功");
    }else{
        NSLog(@"验收记录新增失败");
    }
}

#pragma mark - 先新增附件表
-(NSArray *)insertAttachment:(NSString *)recordIds {
    NSArray *rFileArr;
    if (self.selectedAssetURLs.count > 0) {
        rFileArr = [LSUtility insertAttachmentFromArray:self.selectedAssetURLs andRecordId:recordIds andType:@"PROCESS_03" andRecifyState:@"0"];
    }
    return rFileArr;
}




#pragma mark UIActionSheet M

- (void)showActionForPhoto{
    [self.view endEditing:YES];
    //    @weakify(self);
    [[UIActionSheet bk_actionSheetCustomWithTitle:nil buttonTitles:@[@"拍照", @"从相册选择"] destructiveTitle:nil cancelTitle:@"取消" andDidDismissBlock:^(UIActionSheet *sheet, NSInteger index) {
        
        [self photoActionSheet:sheet DismissWithButtonIndex:index];
        
    }] showInView:self.view];
}

- (void)photoActionSheet:(UIActionSheet *)sheet DismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        //拍照
        if (_curTweet.tweetImages.count >= 9) {//照片最多这么多
            kTipAlert(@"最多只可选择9张照片，已经选满了。先去掉一张照片再拍照呗～");
            return;
        }
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = NO;//设置可编辑
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];//进入照相界面
        
    }else if (buttonIndex == 1){
        PictureViewController *picCtr=[[PictureViewController alloc]init];
        picCtr.flag=@"file";
        NSMutableArray *array = [self.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
        picCtr.selectedImages = [[NSMutableArray alloc] initWithArray:array];
        picCtr.selectedImageBlock = ^(NSMutableArray *array){
            
            self.selectedAssetURLs = array;
        };
        [self.navigationController pushViewController:picCtr animated:YES];
    }
}

#pragma mark UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    self.curTweet.editImageView = [[EditImageView alloc]initWithImage:image];
    WEAKSELF
    self.curTweet.editImageView.completeBlock = ^(NSString *path) {
        //添加选择附件
        [weakSelf.curTweet addASelectedAssetURL:path];
        [weakSelf.selectedAssetURLs addObject:path];
        //刷新指定行
        [weakSelf.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:3]] withRowAnimation:UITableViewRowAnimationFade];
    };
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}



// 将字典或者数组转化为JSON串
- (NSString *)toJSONData:(id)theData{
    NSString *jsonString = nil;
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData
                                                       options:0
                                                         error:&error];
    
    if ([jsonData length] != 0 && error == nil){
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    } else {
        NSLog(@"转JSON失败%@", error);
    }
    return jsonString;
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end



